package com.lyx.com.lyx.rpc.test.consumer.codec.handler;

import com.alibaba.fastjson.JSONObject;
import com.lyx.rpc.protocol.RpcProtocol;
import com.lyx.rpc.protocol.header.RpcHeaderFactory;
import com.lyx.rpc.protocol.request.RpcRequest;
import com.lyx.rpc.protocol.response.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author by lyx
 * RPC消费者处理器
 */
public class RpcTestConsumerHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcResponse>> {
    private final Logger logger = LoggerFactory.getLogger(RpcTestConsumerHandler.class);

    /**
     * 直接打印服务消费者接收到的从服务提供者响应过来的数据。
     *
     * @param channelHandlerContext
     * @param rpcResponseRpcProtocol
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcProtocol<RpcResponse> rpcResponseRpcProtocol) throws Exception {
        logger.info("服务消费者接收到的数据===>>>{}", JSONObject.toJSONString(rpcResponseRpcProtocol));
    }

    /**
     * channelActive()方法会在服务消费者与服务提供者之间成功建立连接时触发
     * 模拟封装了请求数据协议，并将数据发送到服务提供者
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("发送数据开始...");
        RpcProtocol<RpcRequest> rpcRequestRpcProtocol = new RpcProtocol<>();
        rpcRequestRpcProtocol.setHeader(RpcHeaderFactory.getRpcHeader("jdk"));
        RpcRequest request = new RpcRequest();
        request.setClassName("com.lyx.rpc.test.api.DemoService");
        request.setGroup("lyx");
        request.setMethodName("hello");
        request.setParameters(new Object[]{"lyx"});
        request.setParameterTypes(new Class[]{String.class});
        request.setVersion("1.0.0");
        request.setAsync(false);
        request.setOneway(false);
        rpcRequestRpcProtocol.setBody(request);
        logger.info("服务消费者发送的数据===>>>{}", JSONObject.toJSONString(rpcRequestRpcProtocol));
        ctx.writeAndFlush(rpcRequestRpcProtocol);
        logger.info("发送数据完毕...");
    }
}
